package com.zyq.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 获取发送过来的路径信息，进而进行判断
        String path = request.getPath().toString();
        System.out.println("path = " + path);

        if("/login".equals(path)){
            // 放行
            return chain.filter(exchange);
        }
        return chain.filter(exchange);
        // 其他路径就需要进行校验token
        /*String token = request.getHeaders().getFirst("token");
        // 判断字符串token是否为null
        if(StringUtils.hasText(token)){
            if(JWTUtil.verifyToken(token)){
                return chain.filter(exchange);
            }
        }*/
        // token过期或者没有相应信息
        // 1. 设置状态码
       /* response.setStatusCode(HttpStatus.UNAUTHORIZED);
        // 2. 封装返回数据
        Result<String> result = new Result<>(500,"token存在问题",null);
        // 3.转换成json
        byte[] bytes = JSON.toJSONString(result).getBytes(StandardCharsets.UTF_8);

        //4.调用bufferFactory方法，生成DataBuffer对象
        DataBuffer wrap = response.bufferFactory().wrap(bytes);

        //5.调用Mono中的just方法，返回要写给前端的JSON数据

        return response.writeWith(Mono.just(wrap));*/
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
